﻿using HartConfigTool.HARTCommands.CMDs;
using HartConfigTool.SerialPortUtil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HartConfigTool.UI.DebugWindow
{
    internal sealed class CMDsDebugWinHARTCMD6 : CMD6WritePollingAddress
    {
        public CMDsDebugWinHARTCMD6(SerialPortsManager serialPortManager, string pollingAddr, string loopCurMode) 
            : base(serialPortManager, pollingAddr, loopCurMode) { }

        protected override async Task SendCMDCode()
        {
            byte[] tempAry = new byte[16];
            byte[] cmdCodeBytes;

            CMD6WritePollingAddressCode.pollingAddr = Convert.ToByte(PollingAddress);
            CMD6WritePollingAddressCode.loopCurModeCode = (EnumLoopCurrentModeCodes)(HARTProtocolV7.LoopCurrentModeCodes.FirstOrDefault(kvp => kvp.Value == LoopCurrentMode).Key);

            cmdCodeBytes = StructToBytes<CMD6WritePollingAddressCodeStruct>(CMD6WritePollingAddressCode);

            Array.Copy(cmdCodeBytes, 5, tempAry, 0, 10);
            cmdCodeBytes[cmdCodeBytes.Length - 1] = HARTProtocolV7.GetCRC(tempAry, (byte)10);

            serialPortManager.DebugMessage("[" + DateTime.Now + "]:-->" + HARTProtocolV7.HexToString(cmdCodeBytes) + "\r\n");

            await serialPortManager.SendCMD(cmdCodeBytes);
        }
        public override async Task ParseResponse(byte[] responseData)
        {
            await Task.Run(() =>
            {
                byte[] data = null;

                data = serialPortManager.GetRxBufferData();

                // Debug Message
                serialPortManager.DebugMessage("[" + DateTime.Now + "]:<--" + HARTProtocolV7.HexToString(data) + "\r\n");

                this.serialPortManager.RxDataClear();
            });
        }
    }
}
